//
//  AddMoreViewController.m
//  CasesOfEntry
//
//  Created by 聚财通 on 16/2/17.
//  Copyright © 2016年 付正. All rights reserved.
//  添加新病例信息页面

#import "AddMoreViewController.h"
#import "YTKKeyValueStore.h"
#import "FZHPickerView.h"

@interface AddMoreViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,FZHPickerViewDelegate>
{
    UITableView *myTableV;
    FZHPickerView *sexPickerView;
    FZHPickerView *agePickerView;
    
    UILabel *nameLabel;
    UILabel *ageLabel;
    UILabel *sexLabel;
    UILabel *phoneLabel;
    UILabel *idLabel;
    UILabel *describeLabel;
    UIButton *btn;
    
    UITextField *nameTF;
    UITextField *ageTF;
    UITextField *sexTF;
    UITextField *phoneTF;
    UITextField *idTF;
    UITextField *describeTF;
    
    YTKKeyValueStore *store;
    NSMutableArray *array;
    NSMutableArray *nameArray;
}
@end

@implementation AddMoreViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    leftButton.hidden = NO;
    
    self.navigationItem.title = @"添加新信息";
    
    array = [[NSMutableArray alloc]init];
    nameArray = [[NSMutableArray alloc]init];
    
    [self makeTableView];
    [self makeUI];
    [self makePickerView];
}

-(void)viewWillAppear:(BOOL)animated
{
    idTF.text = [FZPublic getSystemTime];
}

-(void)viewDidAppear:(BOOL)animated
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

-(void)viewDidDisappear:(BOOL)animated
{
    nameTF.text = nil;
    ageTF.text = @"1";
    sexTF.text = @"男";
    phoneTF.text = nil;
    idTF.text = nil;
    describeTF.text = nil;
}

#pragma mark --- 创建界面
-(void)makeUI
{
    nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 70, 35)];
    nameLabel.text = @"姓名：";
    nameLabel.textAlignment = NSTextAlignmentCenter;
    
    nameTF = [[UITextField alloc]initWithFrame:CGRectMake(95, 10, Dewidth-120, 35)];
    nameTF.layer.borderWidth = 1.0;
    nameTF.layer.borderColor = [UIColor lightGrayColor].CGColor;
    nameTF.placeholder = @" (姓名*)";
    nameTF.delegate = self;
    
    ageLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 70, 35)];
    ageLabel.text = @"年龄：";
    ageLabel.textAlignment = NSTextAlignmentCenter;
    
    ageTF = [[UITextField alloc]initWithFrame:CGRectMake(95, 10, Dewidth-120, 35)];
    ageTF.layer.borderWidth = 1.0;
    ageTF.layer.borderColor = [UIColor lightGrayColor].CGColor;
    ageTF.text = @"0";
    ageTF.delegate = self;
    ageTF.keyboardType = UIKeyboardTypeNumberPad;
    
    sexLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 70, 35)];
    sexLabel.text = @"性别：";
    sexLabel.textAlignment = NSTextAlignmentCenter;
    
    sexTF = [[UITextField alloc]initWithFrame:CGRectMake(95, 10, Dewidth-120, 35)];
    sexTF.layer.borderWidth = 1.0;
    sexTF.layer.borderColor = [UIColor lightGrayColor].CGColor;
    sexTF.text = @"男";
    sexTF.delegate = self;
    
    phoneLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 70, 35)];
    phoneLabel.text = @"手机号：";
    phoneLabel.textAlignment = NSTextAlignmentCenter;
    
    phoneTF = [[UITextField alloc]initWithFrame:CGRectMake(95, 10, Dewidth-120, 35)];
    phoneTF.layer.borderWidth = 1.0;
    phoneTF.layer.borderColor = [UIColor lightGrayColor].CGColor;
    phoneTF.placeholder = @" (手机号*)";
    phoneTF.delegate = self;
    phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    
    idLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 70, 35)];
    idLabel.text = @"编号：";
    idLabel.textAlignment = NSTextAlignmentCenter;
    
    idTF = [[UITextField alloc]initWithFrame:CGRectMake(95, 10, Dewidth-120, 35)];
    idTF.enabled = false;
    idTF.keyboardType = UIKeyboardTypeNumberPad;
    
    describeLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 70, 35)];
    describeLabel.text = @"描述：";
    describeLabel.textAlignment = NSTextAlignmentCenter;
    
    describeTF = [[UITextField alloc]initWithFrame:CGRectMake(95, 10, Dewidth-120, 35)];
    describeTF.layer.borderWidth = 1.0;
    describeTF.layer.borderColor = [UIColor lightGrayColor].CGColor;
    describeTF.placeholder = @" (描述)";
    describeTF.delegate = self;
    
    btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(30, 10, Dewidth-60, 45);
    [btn setTitle:@"保存" forState:UIControlStateNormal];
    [btn setBackgroundImage:[[UIImage imageNamed:@"nav_bg" ]resizableImageWithCapInsets:UIEdgeInsetsMake(5, 3, 5, 3)] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(didClickBtn) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark --- 创建tableview
-(void)makeTableView
{
    myTableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Dewidth, Deheight) style:UITableViewStyleGrouped];
    myTableV.delegate = self;
    myTableV.dataSource = self;
    myTableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:myTableV];
}

#pragma mark --- 创建pickerView
-(void)makePickerView
{
    sexPickerView = [[FZHPickerView alloc]initWithFrame:CGRectMake(0, Deheight - 200, Dewidth, 200)];
    sexPickerView.fzdelegate = self;
    sexPickerView.proTitleList = [[NSArray alloc]initWithObjects:@"男",@"女",nil];
    
    agePickerView = [[FZHPickerView alloc]initWithFrame:CGRectMake(0, Deheight - 200, Dewidth, 200)];
    agePickerView.fzdelegate = self;
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    for (int i = 1; i<131; i++) {
        [arr addObject:[NSString stringWithFormat:@"%d",i]];
    }
    agePickerView.proTitleList = [NSArray arrayWithArray:arr];
}

#pragma mark --- 分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark --- 每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
}

#pragma mark - cell重用
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [[UITableViewCell alloc]init];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor colorWithRed:239 / 255.0 green:239 / 255.0 blue:239 / 255.0 alpha:1];
    
    if (indexPath.row == 1) {
        [cell addSubview:idLabel];
        [cell addSubview:idTF];
    }
    if (indexPath.row == 2) {
        [cell addSubview:nameLabel];
        [cell addSubview:nameTF];
    }
    if (indexPath.row == 3) {
        [cell addSubview:ageLabel];
        [cell addSubview:ageTF];
        ageTF.inputView = agePickerView;
    }
    if (indexPath.row == 4) {
        [cell addSubview:sexLabel];
        [cell addSubview:sexTF];
        sexTF.inputView = sexPickerView;
    }
    if (indexPath.row == 5) {
        [cell addSubview:phoneLabel];
        [cell addSubview:phoneTF];
    }
    if (indexPath.row == 6) {
        [cell addSubview:describeLabel];
        [cell addSubview:describeTF];
    }
    if (indexPath.row == 7) {
        [cell addSubview:btn];
    }
    
    return cell;
}

#pragma mark --- 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 15;
    }
    else if (indexPath.row == 6) {
        return 65;
    }
    return 55;
}

#pragma mark --- 表头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

#pragma mark --- 点击保存按钮
-(void)didClickBtn
{
    if ([nameTF.text isEqualToString:@""] || [ageTF.text isEqualToString:@""] || [sexTF.text isEqualToString:@""] || [idTF.text isEqualToString:@""] || [phoneTF.text isEqualToString:@""]) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"信息填写不完整(*为必填项)" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    else if ([FZPublic judgeTheTelephone:phoneTF.text] != YES) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"手机号码格式不正确" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    else{
        [self saveData];
    }
}

#pragma mark --- 保存数据
-(void)saveData
{
    // Demo
    NSString *tableName = nameTF.text;
    store = [[YTKKeyValueStore alloc] initDBWithName:@"test.db"];
    [store createTableWithName:tableName];
    NSDictionary *user = @{@"id": idTF.text, @"name": nameTF.text, @"age": ageTF.text, @"sex":sexTF.text, @"phone":phoneTF.text, @"describe":describeTF.text};
    [store putObject:user withId:idTF.text intoTable:tableName];
    //先取出原来的
    NSDictionary *dic = [store getObjectById:@"101101011244101101011244" fromTable:@"user_table"];
    if (dic) {
        [array removeAllObjects];
        [nameArray removeAllObjects];
        [array addObject:idTF.text];
        [nameArray addObject:nameTF.text];
        NSMutableArray *arr = dic[@"id"];
        for (int i = 0 ; i < arr.count; i++) {
            [array addObject:arr[i]];
            [nameArray addObject:dic[@"table"][i]];
        }
    }
    else{
        [nameArray addObject:nameTF.text];
        [array addObject:idTF.text];
    }
    
    NSDictionary *dict = @{@"id":array,@"table":nameArray};
    [store createTableWithName:@"user_table"];
    [store putObject:dict withId:@"101101011244101101011244" intoTable:@"user_table"];
    
    //返回
    [self leftButtonAction:nil];
}

#pragma mark --- 开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int line;
    if (textField == phoneTF) {
        line = 5;
    }
    else if (textField == describeTF) {
        line = 6;
    }
    else{
        line = 0;
    }
    int offset = frame.origin.y + line*55 + 118 - (Deheight - 216.0);//键盘高度216
    
    //动画效果
    [UIView animateWithDuration:0.3 animations:^{
        //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
        if (offset > 0) {
            self.view.frame = CGRectMake(0.0f, -offset, Dewidth, Deheight);
        }
        else {
            self.view.frame =CGRectMake(0, 64, Dewidth, Deheight);
        }
    }];
}

#pragma mark --- 当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark --- 点击屏幕空白处收起键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    //动画效果
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame =CGRectMake(0, 64, Dewidth, Deheight);
    }];
}

#pragma mark --- pickerView代理方法
-(void)didSelectedPickerView:(UIPickerView *)pickerView RowText:(NSString *)text
{
    if (pickerView == sexPickerView) {
        sexTF.text = text;
    }
    if (pickerView == agePickerView) {
        ageTF.text = text;
    }
}

#pragma mark --- 返回按钮
-(void)leftButtonAction:(id)sender
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
